package server.controller;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import plug.result.RetResponse;
import plug.result.RetResult;
import server.dao.ShopOrderDao;
import server.dao.UsersDao;
import server.model.dto.Relationship;
import server.model.dto.UserTuDto;
import server.model.entity.Users;
import server.service.MenuService;
import server.tool.tool.BeanUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 创建人:    xvzhe
 * 创建时间:
 * 修改时间:
 * 版本:      v1.0
 */
@RestController
@RequestMapping("v2/api")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private UsersDao usersDao;

    @Autowired
    private ShopOrderDao shopOrderDao;

    @CrossOrigin(origins = "*")
    @GetMapping("/menu/{userId}")
    public RetResult findAll(@PathVariable String userId) {
        return menuService.findAll(userId);
    }

    @CrossOrigin(origins = "*")
    @GetMapping("/info")
    public RetResult info() {
        HashMap<String, Object> mp = Maps.newHashMap();
        String format = DateUtil.format(new Date(), "yyyy-MM-dd");
        mp.put("daySumRegist",usersDao.findTime(format).size());
        mp.put("sumRegist",usersDao.findAll().size());
        mp.put("daySum",shopOrderDao.findTime(format).size());
        Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        mp.put("sum",users.getPerformance());
        return RetResponse.makeOKRsp(mp);
    }


    @GetMapping("/tj/tu/{userId}")
    @ApiOperation("邀请")
    @CrossOrigin(origins = "*")
    public RetResult tu(@PathVariable String userId) {
        Users uself = usersDao.findById(userId).get();
        UserTuDto ud = BeanUtil.convertToBean(uself, UserTuDto.class);
        StringBuilder sp = new StringBuilder();
        sp.setLength(0);
        sp.append("<br>用户名称：" + ud.getName());
        sp.append("<br>手机号：" + ud.getMobile());
        sp.append("<br>级别：" + ud.getGrade().getDisplay());
        sp.append("<br>我的业绩：" + ud.getSelfPerformance());
        sp.append("<br>团队业绩：" + (ud.getPerformance()-ud.getSelfPerformance()));
        ud.setTitle(sp.toString());
        Relationship relationshipx = new Relationship();
        relationshipx.setChildren_num(0);
        relationshipx.setParent_num(0);
        relationshipx.setSibling_num(0);
        ud.setRelationship(relationshipx);
        List<UserTuDto> lx = usersDao.findByTreeLike(userId).stream().map(item -> {
            return BeanUtil.convertToBean(item, UserTuDto.class);
        }).collect(Collectors.toList());
        Map<Integer, List<UserTuDto>> mp = lx.stream().collect(Collectors.groupingBy(UserTuDto::getTreeNum));
        Map<Integer, List<UserTuDto>> result = new LinkedHashMap<>();
        mp.entrySet().stream()
                .sorted(Map.Entry.<Integer, List<UserTuDto>>comparingByKey().reversed())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        List<UserTuDto> list = Lists.newLinkedList();
        lx.forEach(i -> {
            sp.setLength(0);
            sp.append("<br>用户名称：" + i.getName());
            sp.append("<br>手机号：" + i.getMobile());
            sp.append("<br>级别：" + i.getGrade().getDisplay());
            sp.append("<br>我的业绩：" + i.getSelfPerformance());
            sp.append("<br>团队业绩：" + (i.getPerformance()-i.getSelfPerformance()));
            Relationship relationship = new Relationship();
            relationship.setChildren_num(0);
            relationship.setParent_num(1);
            relationship.setSibling_num(0);
            i.setRelationship(relationship);
        });
        List<Integer> keys = new ArrayList<>(result.keySet());
        for (int i = 0; i < keys.size(); i++) {
            List<UserTuDto> self = result.get(keys.get(i));
            if (i == 0) {
                self.forEach(it -> {
                    sp.setLength(0);
                    sp.append("<br>用户名称：" + it.getName());
                    sp.append("<br>手机号：" + it.getMobile());
                    sp.append("<br>级别：" + it.getGrade().getDisplay());
                    sp.append("<br>我的业绩：" + it.getSelfPerformance());
                    sp.append("<br>团队业绩：" + (it.getPerformance()-it.getSelfPerformance()));
                    it.setTitle(sp.toString());
                    Relationship relationship = new Relationship();
                    relationship.setChildren_num(0);
                    relationship.setParent_num(1);
                    relationship.setSibling_num(self.size());
                    it.setRelationship(relationship);
                });
                result.put(keys.get(0), self);
            }
            if (i == keys.size() - 1) {
                ud.setChildren(self);
                Relationship relationship = new Relationship();
                relationship.setChildren_num(ud.getChildren() == null ? 0 : ud.getChildren().size());
                relationship.setParent_num(1);
                relationship.setSibling_num(self.size());
                ud.setRelationship(relationship);
                continue;
            }
            List<UserTuDto> par = result.get(keys.get(i + 1));
            Map<String, List<UserTuDto>> mpar = self.stream().collect(Collectors.groupingBy(UserTuDto::getParentId));
            par.forEach(item -> {
                sp.setLength(0);
                sp.append("<br>用户名称：" + item.getName());
                sp.append("<br>手机号：" + item.getMobile());
                sp.append("<br>级别：" + item.getGrade().getDisplay());
                sp.append("<br>我的业绩：" + item.getSelfPerformance());
                sp.append("<br>团队业绩：" + (item.getPerformance()-item.getSelfPerformance()));
                item.setTitle(sp.toString());
                item.setChildren(mpar.get(item.getId()));
                Relationship relationship = new Relationship();
                relationship.setChildren_num(item.getChildren() == null ? 0 : item.getChildren().size());
                relationship.setParent_num(1);
                relationship.setSibling_num(self.size());
                item.setRelationship(relationship);
            });
            result.put(keys.get(i + 1), par);
        }
        return RetResponse.makeOKRsp(ud);
    }
}
